<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class ProcessTransaction extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'process:transaction';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Process transactions with error handling';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        DB::beginTransaction(); // 开始外部事务

        try {
            foreach ( range(1, 3) as $i ) {
                try {
                    DB::beginTransaction(); // 开始内部事务

                    // 执行内部事务的操作
                    DB::table('student')->insert([
                        'unit_name' => 'value '.$i,
                        'create_time'=>date('Y-m-d H:i:s',time()),
                    ]);

                    if ($i == 2) {
                        // 触发异常
                        throw new \Exception('Simulated error in iteration '.$i);
                    }

                    // 提交内部事务
                    DB::commit();
                } catch (\Exception $e) {
                    // 如果内部事务失败，回滚内部事务
                    DB::rollBack();
                    // 选择是否在此处处理错误
                    $this->error('Error in iteration '.$i.': '.$e->getMessage());
                    // 如果希望抛出异常以停止外部事务，可以在这里选择抛出异常
                    // throw $e;
                }
            }
            throw new \Exception('dfsasfda');
            // 提交外部事务
            DB::commit();
            $this->info('Transaction completed successfully.');
        } catch (\Exception $e) {
            // 如果外部事务失败，回滚外部事务
            DB::rollBack();
            $this->error('Transaction failed: '.$e->getMessage());

            return 1; // 返回非零状态码表示失败
        }

        return 0; // 返回零状态码表示成功
    }
}